<?php


namespace common\helpers;


use Yii;

class DataHelper
{

    const WX_URL = 'https://api.weixin.qq.com';

    public static function getWxAccessToken()
    {
        $access_token = Yii::$app->cache->get('access_token');
        if (!$access_token) {
            $url = self::WX_URL . "/cgi-bin/token?grant_type=client_credential&appid=" . Yii::$app->params['wechat']['app_id'] . "&secret=" . Yii::$app->params['wechat']['secret'];
            $res = self::curl_get_https($url);
            if ($res) {
                $res = json_decode($res, true);
                $access_token = $res['access_token'];
                Yii::$app->cache->set('access_token', $access_token, 7200);
            }
        }

        return $access_token;
    }

    public static function getWxUserInfo1($code)
    {
        $url = self::WX_URL . "/sns/oauth2/access_token?appid=" . Yii::$app->params['wechat']['app_id'] . "&secret=" . Yii::$app->params['wechat']['secret'] . "&code=" . $code . "&grant_type=authorization_code";
        $res = self::curl_get_https($url);
        if ($res) {
            $res = json_decode($res, true);
            $openid = $res['openid'];
            $access_token = DataHelper::getWxAccessToken();
            if ($access_token) {
                $url = self::WX_URL . "/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid;
                $res = self::curl_get_https($url);
                if ($res) {
                    return json_decode($res, true);
                }
            }

        }
        return [];
    }

    public static function getOpenid($code)
    {
        $url = self::WX_URL . "/sns/oauth2/access_token?appid=" . Yii::$app->params['wechat']['app_id'] . "&secret=" . Yii::$app->params['wechat']['secret'] . "&code=" . $code . "&grant_type=authorization_code";
        $res = self::curl_get_https($url);
        if ($res) {
            $res = json_decode($res, true);
            if (isset($res['openid'])) {
                return $res['openid'];
            }
        }
        return '';
    }

    public static function getOpenid1($js_code)
    {
        $url = self::WX_URL . "/sns/jscode2session?appid=" . Yii::$app->params['wechat']['app_id'] . "&secret=" . Yii::$app->params['wechat']['secret'] . "&js_code=" . $js_code . "&grant_type=authorization_code&connect_redirect=1";
        $res = self::curl_get_https($url);

        if ($res) {
            $res = json_decode($res, true);
            if (isset($res['openid'])) {
                return $res['openid'];
            }
        }
        return '';
    }

    public static function getUserOAuth2($code)
    {
        $url = self::WX_URL . "/sns/oauth2/access_token?appid=" . Yii::$app->params['wechat']['app_id'] . "&secret=" . Yii::$app->params['wechat']['secret'] . "&code=" . $code . "&grant_type=authorization_code";
        $res = self::curl_get_https($url);
        if ($res) {
            $res = json_decode($res, true);
            return $res;
        }
        return '';
    }

    public static function getWxUserInfo($openid)
    {
        $access_token = DataHelper::getWxAccessToken();
        if ($access_token) {
            $url = self::WX_URL . "/cgi-bin/user/info?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
            $res = self::curl_get_https($url);
            if ($res) {
                return json_decode($res, true);
            }
        }
        return [];
    }

    public static function getWxUserInfo2($openid, $access_token)
    {
        $url = self::WX_URL . "/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = self::curl_get_https($url);
        if ($res) {
            return json_decode($res, true);
        }
        return [];
    }

    public static function getJSAPITicket()
    {
        $js_api_ticket = Yii::$app->cache->get('js_api_ticket');
        if (!$js_api_ticket) {
            $access_token = DataHelper::getWxAccessToken();
            if ($access_token) {
                $url = self::WX_URL . '/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=jsapi';
                $res = self::curl_get_https($url);
                if ($res) {
                    $res = json_decode($res, true);
                    if ($res['ticket']) {
                        $js_api_ticket = $res['ticket'];
                        Yii::$app->cache->set($js_api_ticket, 7200);
                    }
                }
            }
        }
        return $js_api_ticket;
    }

    public static function getWxConfig($url)
    {
        $ticket = DataHelper::getJSAPITicket();
        if ($ticket) {
            $noncestr = self::getRandStr(16);
            $time = time();
            $string = 'jsapi_ticket=' . $ticket . '&noncestr=' . $noncestr . '&timestamp=' . $time . '&url=' . $url;
            // Yii::info('string:');
            // Yii::info($string);
            // Yii::info('noncestr:');
            // Yii::info($noncestr);
            // Yii::info('time:');
            // Yii::info($time);
            return [
                'debug' => false,
                'appId' => Yii::$app->params['wechat']['app_id'],
                'timestamp' => $time,
                'nonceStr' => $noncestr,
                'signature' => sha1($string),
                'jsApiList' => [],
            ];
        }
        return [];
    }

    public static function getRandStr($length)
    {
        $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        return substr($randStr, 0, $length);//substr(string,start,length);返回字符串的一部分
    }

    public static function curl_get_https($url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

    function curl_post_https($url, $data, $header)
    { // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        if ($header) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($curl, CURLINFO_HEADER_OUT, true); /* 请求头 */
        curl_setopt($curl, CURLOPT_HEADER, false); /* 返回头 */
        #curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        #curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        #curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        $tmpInfo = curl_exec($curl); // 执行操作
        //通过curl_getinfo()可以得到请求头的信息
        #var_dump(curl_getinfo($curl));

        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

}